import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * This represents the knowledge base of a single agent / player.
 */
public class KnowledgeBase {
	
	// maps
	private final Map<Integer, ArrayList<String>> likesKb;
	private final Map<Integer, ArrayList<String>> dislikesKb;
	private final Map<Integer, ArrayList<Integer>> friends;
	
	public KnowledgeBase() {
		this.likesKb = new HashMap<Integer, ArrayList<String>>();
		this.dislikesKb = new HashMap<Integer, ArrayList<String>>();
		this.friends = new HashMap<Integer, ArrayList<Integer>>();
	}
	
	private ArrayList<String> get(final Integer agentId, final Map<Integer, ArrayList<String>> selectedKb) {
		ArrayList<String> value = selectedKb.get(agentId);
		if (value == null) {
			value = new ArrayList<String>();
			selectedKb.put(agentId, value);
		}
		return selectedKb.get(agentId);
	}

	/**
	 * Adds an answer to the knowledge base. In practice, this stores either a like or
	 * dislike for an agent (provided inside of the answer).
	 */
	public void addAnswer(final Answer answer) {
		Map<Integer, ArrayList<String>> selectedKb 
			= (answer.getType().equals(AnswerType.LIKE)) ? likesKb : dislikesKb;
		
		ArrayList<String> value = get(answer.getAgentId(), selectedKb);
		if (!value.contains(answer.getVariable())) {
			value.add(answer.getVariable());
		}
	}
	
	public void addFriend(final Integer keyFriendId, final Integer valueFriendId) {
		ArrayList<Integer> value = friends.get(keyFriendId);
		if (value == null) {
			friends.put(keyFriendId, new ArrayList<Integer>());
			value = friends.get(keyFriendId);
		}
		
		if (!value.contains(valueFriendId)) {
			value.add(valueFriendId);
		}
	}
	
	public ArrayList<String> getLikes(final Integer agentId) {
		return get(agentId, likesKb);
	}
	
	public ArrayList<String> getDislikes(final Integer agentId) {
		return get(agentId, dislikesKb);
	}
	
	public ArrayList<String> getFriends(final Integer agentId) {
		ArrayList<Integer> value = friends.get(agentId);
		if (value == null) {
			friends.put(agentId, new ArrayList<Integer>());
			value = friends.get(agentId);
		}
		ArrayList<String> names = new ArrayList<String>();
		for (Integer id : value) {
			names.add(Global.agents.get(id).getAgentname());
		}
		return names;
	}
}
